package com.example.wishstar.repository;

import android.os.AsyncTask;
import android.util.Log;

import androidx.lifecycle.LiveData;

import com.example.wishstar.api.Api;
import com.example.wishstar.db.UserDao;
import com.example.wishstar.model.Users;
import com.example.wishstar.utils.ApiResponse;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class UsersRepository {
    private String TAG = "UsersRepository";
    private UserDao usersDao;
    private Api api;

    public UsersRepository(UserDao usersDao, Api api) {
        this.usersDao = usersDao;
        this.api = api;
    }

    public LiveData<Users> getUsers(int userId) {
        refresh(userId);
        return usersDao.getUsersByUserId(userId);
    }

    public void refresh(Integer userId) {
        api.getUsers(userId).enqueue(new Callback<ApiResponse<Users>>() {
            @Override
            public void onResponse(Call<ApiResponse<Users>> call, Response<ApiResponse<Users>> response) {
                if(response.body()!= null && response.body().code == 200) {
                    Log.e(TAG, "refresh->response" + response.body());
                    insertUsers(response.body().getData());
                }
            }

            @Override
            public void onFailure(Call<ApiResponse<Users>> call, Throwable t) {
                Log.e(TAG, "refresh()->onFailure()");
            }
        });
    }

    public void insertUsers(Users users) {
        AsyncTask.execute(new Runnable() {
            @Override
            public void run() {
                usersDao.insertUsers(users);
                Log.e(TAG, "insertUsers()->" + users);
            }
        });
    }

    public void logOut(int userId) {
        AsyncTask.execute(new Runnable() {
            @Override
            public void run() {
                usersDao.updateStateByuserId(0, userId);
            }
        });
    }
}
